package com.softserveinc.lahire.builders;

import java.awt.PageAttributes.MediaType;
import java.io.BufferedReader;
import java.io.File;
import java.net.URL;
import java.util.StringTokenizer;

import com.softserveinc.lahire.configurator.Configurator;

abstract class RequestBuilder {

	protected Request request;
	protected BufferedReader in;

	public Request getRequest() {

		return request;
	}

	public void createNewRequest(BufferedReader in, String url) {
		request = new Request();

		
		// parse the file by /'s and build a local file
		
			
		StringTokenizer tok = new StringTokenizer(url, "/",true);
		String recoursePath = addSlash(Configurator.getInstance().getByTag(
				"httpRoot"));

		while (tok.hasMoreElements()) {
			String e = (String) tok.nextElement();
			if (!e.trim().equalsIgnoreCase("/")) {
				if (e.equals("..") || e.equals(".")) {
				}
				recoursePath += e;
			} else
				recoursePath = addSlash(recoursePath);
		}

		// if there is no file specified, default
		// to index.html

		/*if (recoursePath.endsWith(File.separator)) {
			recoursePath = recoursePath + "index.html";
		}*/

		//TODO: Remake this
		
		request.setUrl(url);
		request.setRecoursePath(recoursePath);
		String[] ext = url.split("\\.");

		if (ext.length > 1) {
			request.setContentType(Configurator.mimeType.get(ext[1]));
		}

		// Send the rest of HTTP request to builders

		this.in = in;

	}

	private String addSlash(String path) {
		path = path.trim();
		if (path.endsWith("" + File.separatorChar))
			return path;
		else
			return path + File.separatorChar;
	}

	public abstract void buildHeaders();

	public abstract void buildParameters();

}
